package com.codemes.happylist.modules.iciba;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.codemes.happylist.CodemesToolMain;
import com.codemes.happylist.config.ThreadPoolConfig;
import com.codemes.happylist.utils.FilePathConst;
import com.codemes.happylist.views.loading.CodemesLoading;
import de.felixroske.jfxsupport.FXMLController;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.scene.media.MediaView;
import javafx.util.Duration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.io.File;
import java.net.URL;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.ResourceBundle;

/**
 * @author nscoffee
 */
@FXMLController
@Slf4j
public class IcibaDailyPhaseController implements Initializable {

    @FXML
    Hyperlink link_content;
    @FXML
    ImageView img_picture;
    @FXML
    ImageView img_picture2;
    @FXML
    ImageView img_picture3;
    @FXML
    ImageView img_picture4;
    @FXML
    Hyperlink link_note;
    @FXML
    Button btn_play_tts;

    @FXML
    Button btn_pre;
    @FXML
    Button btn_next;
    @FXML
    ImageView img_fenxiang_img;
    @FXML
    DatePicker dp_cur;

    private Date curDate;

    EventHandler<ActionEvent> dp_cur_selectEventHandler;

    @Resource(name = ThreadPoolConfig.POOL_BEAN_NAME)
    ThreadPoolTaskExecutor executor;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {

        curDate = new Date();
        Platform.runLater(new ICibaDailyLoadAble(curDate));
        refreshDatePicker(curDate);

        dp_cur.setEditable(false);
        dp_cur_selectEventHandler = event -> {
            log.info(" on action event ->>>>{}",event);
            DatePicker dp = (DatePicker) event.getSource();
            LocalDate selectDate = dp.getValue();
            log.info("select date -> {}",selectDate);
            log.info("year ->{} month -> {} day -> {}",selectDate.getYear(),selectDate.getMonthValue(),selectDate.getDayOfMonth());
            Calendar selCal = Calendar.getInstance();
            selCal.set(selectDate.getYear(),selectDate.getMonthValue()-1,selectDate.getDayOfMonth());
            log.info("convert localdate to caleander ->{}",selCal.getTime());
            curDate = selCal.getTime();
            loadingDailyPhase(curDate);
        };
        dp_cur.setOnAction(dp_cur_selectEventHandler);
    }

    private void refreshDatePicker(Date curDate){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(curDate);
        dp_cur.setOnAction(null);
        dp_cur.setValue(LocalDate.of(calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH)+1,calendar.get(Calendar.DAY_OF_MONTH)));
        dp_cur.setOnAction(dp_cur_selectEventHandler);
    }

    public void loadIcibaDailyPhase(Date date){

        log.info("loadIcibaDailyPhase date -> {}",date);

        IcibaDailyDTO icibaDailyDTO = IcibaDailyPhaseUtil.getDailyPhase(date);

        link_content.setText(icibaDailyDTO.getContent());
        link_note.setText(icibaDailyDTO.getNote());
        link_content.setOnAction(e->{
            openWithLocalBrowse(date);
        });
        link_note.setOnAction((e->{
            openWithLocalBrowse(date);
        }));

        img_picture.setImage(new Image(icibaDailyDTO.getPicture()));
        img_picture.setVisible(false);
        img_picture.setManaged(false);
        img_picture.setFitHeight(0);

        Image picture2 = new Image(icibaDailyDTO.getPicture2());
        img_picture2.setImage(picture2);

        img_picture3.setImage(new Image(icibaDailyDTO.getPicture3()));
        img_picture3.setVisible(false);
        img_picture3.setManaged(false);
        img_picture3.setFitHeight(0);

        img_picture4.setImage(new Image(icibaDailyDTO.getPicture4()));
        img_picture4.setVisible(false);
        img_picture4.setManaged(false);
        img_picture4.setFitHeight(0);

        img_fenxiang_img.setImage(new Image(icibaDailyDTO.getFenxiang_img()));

        String tts = icibaDailyDTO.getTts();

        btn_play_tts.setOnAction(event -> {
            CodemesLoading loading = CodemesLoading.of(CodemesToolMain.mainStage,"加载中...",10,0.1);
            loading.show();

            log.info("点击播放按钮，播放英文音频 > {}",tts);
            String fileName = tts.substring(tts.lastIndexOf("/"));
            File destFile = new File(FilePathConst.RESOURCES_DIR_ICIBA+ fileName);
            if(!destFile.exists()){
                log.info("download tts file to path -> {}",destFile.getAbsolutePath());
                HttpUtil.downloadFile(tts,destFile);
            }
            try {
                String localFilePath = destFile.toURI().toURL().toString();
                log.info("点击播放按钮，播放英文音频 > {}",localFilePath);
                Media media = new  Media(tts);
                media.setOnError(() -> log.error("media {} error ->{}",localFilePath, media.getError()));
                MediaPlayer mediaPlayer = new MediaPlayer(media);
                mediaPlayer.setOnError(() -> log.error("mediaPlayer play file {} occur error -> {}",localFilePath,mediaPlayer.getError()));
                // 设置音量
                mediaPlayer.setVolume(1.0);
                // 设置开始时间
                mediaPlayer.setStartTime(Duration.seconds(0));
                log.info("media source ->{}",media.getSource());
                mediaPlayer.play();
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                loading.close();
            }
        });

        btn_pre.setOnMouseClicked(event -> {
            curDate = DateUtil.offsetDay(curDate,-1);
            loadingDailyPhase(curDate);
        });
        btn_next.setOnMouseClicked(event -> {
            String nextDateFormat = DateUtil.format(curDate,"yyyy-MM-dd");
            Date nextDate = DateUtil.parse(nextDateFormat,"yyyy-MM-dd");
            nextDate = DateUtil.offsetDay(nextDate,1);
            log.info("金山词霸 每日一句 后一天 nextDate={}",nextDate);
            Date now = new Date();
            if(nextDate.getTime()>now.getTime()){
                return;
            }
            curDate = nextDate;
            loadingDailyPhase(curDate);
        });
    }

    private void openWithLocalBrowse(Date date) {
        String url = "http://news.iciba.com/views/dailysentence/daily.html#!/detail/title/"+DateUtil.format(date,"yyyy-MM-dd");
        try {
            CodemesToolMain.hostServices.showDocument(url);
        } catch (Exception e) {
            log.error("open browse error ->{}",e);
            Alert alert = new Alert(Alert.AlertType.ERROR,"打开本地浏览器异常，"+e.getMessage()+"\n 链接->"+url, ButtonType.CLOSE);
            alert.show();
        }
//        Desktop desktop = Desktop.getDesktop();
//        try {
//            desktop.browse(new URI(url));
//        } catch (IOException | URISyntaxException ex) {
//            ex.printStackTrace();
//        }
    }

    private void loadingDailyPhase(Date curDate){
        CodemesLoading.of(CodemesToolMain.mainStage, "加载"+ DateUtil.format(curDate,"yyyy-MM-dd")+"的每日一句...", 0.5, new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                log.info("金山词霸 每日一句 后一天 > {}",curDate);
                Platform.runLater(new ICibaDailyLoadAble(curDate));
                refreshDatePicker(curDate);
                return null;
            }
        }).show();
    }


    class ICibaDailyLoadAble implements Runnable{
        Date curDate;
        ICibaDailyLoadAble(Date date){
            this.curDate = date;
        }
        @Override
        public void run() {
            loadIcibaDailyPhase(curDate);
        }
    }
}
